package com.junxonline.instant.admin.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.junxonline.instant.common.util.common.RedisUtils;
import com.junxonline.instant.dao.entity.model.config.Dict;
import com.junxonline.instant.dao.entity.model.config.DictGroup;
import com.junxonline.instant.dao.mapper.config.DictGroupMapper;
import com.junxonline.instant.dao.mapper.config.DictMapper;
import com.junxonline.instant.common.constant.RedisConstant;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 管理后台数据字典缓存初始化处理
 *
 * @author JunX
 * @date 2021-08-30
 */
@Log4j2
@Component
public class InitDictCacheHandler implements CommandLineRunner {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private DictGroupMapper dictGroupMapper;

    @Autowired
    private DictMapper dictMapper;

    @Override
    public void run(String... args) throws Exception {
        try {
            log.info("开始初始化数据字典缓存..");
            // 查询所有的数据字典分组
            List<DictGroup> dictGroupList = dictGroupMapper.selectList(null);
            for (DictGroup dictGroup : dictGroupList) {
                String code = dictGroup.getCode();
                // 查询分组下所有的数据字典
                List<Dict> dictList = dictMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, dictGroup.getId()));
                // 将该分组的数据字典JSON存入缓存中
                redisUtils.set(RedisConstant.KEY_DICT + code, JSON.toJSONString(dictList));
            }
            log.info("初始化数据字典缓存成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化数据字典缓存失败");
        }
    }

}
